package nickthissen.iracing.parsing;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.safety.Cleaner;
import org.jsoup.safety.Whitelist;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Nick on 20-5-13.
 */
public class TagSanitizer
{
    private static Whitelist whitelist = null;
    private static HashMap<String, String[]> tags = new HashMap<String, String[]>()
        {{
            put("a", new String[] {"href"});
            put("b", null);
            put("big", null);
            put("blockquote", null);
            put("br", null);
            put("cite", null);
            put("dfn", null);
            put("div", new String[] {"align"});
            put("em", null);
            put("font", new String[] {"size", "color", "face"});
            put("h1", null);
            put("h2", null);
            put("h3", null);
            put("h4", null);
            put("h5", null);
            put("h6", null);
            put("i", null);
            put("img", new String[] {"src"});
            put("p", null);
            put("small", null);
            put("strike", null);
            put("strong", null);
            put("sub", null);
            put("sup", null);
            put("tt", null);
            put("u", null);
        }};

    private static void createWhitelist()
    {
        if (whitelist != null) return;

        whitelist = new Whitelist();
        for (Map.Entry<String, String[]> tag : tags.entrySet())
        {
            String key = tag.getKey();
            String[] attributes = tag.getValue();

            whitelist.addTags(key);
            if (attributes != null && attributes.length > 0)
            {
                whitelist.addAttributes(tag.getKey(), tag.getValue());
            }
        }
    }

    public static Document sanitize(Document doc)
    {
        createWhitelist();
        Cleaner cleaner = new Cleaner(whitelist);
        return cleaner.clean(doc);
    }

    public static String removeAllTags(Element node)
    {
        Whitelist list = new Whitelist();
        return Jsoup.clean(node.text(), list);
    }
}
